package util

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"regexp"
	"strings"

	"net/http"
)

type TaskObj struct {
	AccIp     string //ip 地址
	ChainType string //iptables Chain: INPUT(default)、DOCKER
	AccTime   int    //时间（小时）
	StarTime  int64  //请求时间
	AccPORT   string //端口
}

var (
	IpReg, _    = regexp.Compile("[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}")
	PortsReg, _ = regexp.Compile("^([\\d]{1,4}\\,)*([\\d]{1,4})+$")
	urlArr      = []string{"http://ip.cn", "http://cip.cc"}
	client      = &http.Client{}
	Se          = SimpleEncrypt{Key: "iptables"}
)

//获取本机ip地址
func GetNetWorkIp() string {
	index := 0
	reqStr := ""
	for {
		if reqStr = doRequest(urlArr[index%len(urlArr)]); reqStr != "" {
			break
		}
		index++
		if index > 5 {
			return ""
		}
	}
	if matchArr := IpReg.FindStringSubmatch(reqStr); len(matchArr) == 1 {
		return matchArr[0]
	}
	return ""
}

func doRequest(url string) string {
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return ""
	}
	request.Header.Add("User-Agent", "curl")

	response, err := client.Do(request)
	if err != nil {
		return ""
	}
	byteBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return ""
	}
	return string(byteBody)
}

//向服务端发送请求
func SendServerMsg(url string, param *TaskObj) (result bool, err error) {
	//添加参数
	bparam, err := json.Marshal(*param)
	if err != nil {
		return false, err
	}
	req, err := http.NewRequest("POST", url, strings.NewReader(string(bparam)))
	if err != nil {
		return false, err
	}

	res, err := client.Do(req)
	if err != nil {
		return false, err
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return false, err
	}

	if !strings.Contains(string(b), "true") {
		return false, errors.New(fmt.Sprintf("响应结果%s", string(b)))
	}
	return true, nil
}
